import { indexPage, indexUpdate, indexRemove } from '@/services/dict';

const defaultQuery = {
  name: '',
  code: '',
  group: '',
  page: 0,
  size: 5,
};

const defaultModal = {
  visible: false,
  data: {},
};

export default {
  namespace: 'dictIndex',

  state: {
    query: {
      ...defaultQuery,
    },
    list: {
      data: [],
      pagination: {},
    },
    modal: { ...defaultModal },
  },

  effects: {
    *fetch({ payload }, { call, put, select }) {
      yield put({ type: 'query', payload });
      const query = yield select(state => state.dictIndex.query);
      const { data } = yield call(indexPage, query);
      yield put({
        type: 'list',
        payload: {
          data: data.content,
          pagination: {
            current: data.number + 1,
            pageSize: data.size,
            total: Number(data.totalElements),
          },
        },
      });
    },
    *reload(_, { put }) {
      yield put({ type: 'fetch', payload: { ...defaultQuery } });
    },
    *update({ payload }, { call }) {
      return yield call(indexUpdate, payload);
    },
    *openModal({ payload }, { put }) {
      yield put({
        type: 'modal',
        payload: {
          data: payload || {},
          visible: true,
        },
      });
    },
    *closeModal(_, { put }) {
      yield put({
        type: 'modal',
        payload: { ...defaultModal },
      });
    },
    *remove({ payload }, { call }) {
      return yield call(indexRemove, payload);
    },
  },

  reducers: {
    query(state, { payload }) {
      return { ...state, query: { ...state.query, ...payload } };
    },
    list(state, { payload }) {
      return { ...state, list: { ...state.list, ...payload } };
    },
    modal(state, { payload }) {
      return { ...state, modal: { ...state.modal, ...payload } };
    },
  },
};
